//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Windows.Media;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal sealed class PaletteRecord : BiffRecord, IWorkbookPass1Record
    {
        readonly List<Color> _colors = new List<Color>();

        public PaletteRecord(StyleSheet styleSheet)
        {
            int toskip = 0;
            foreach (var indexedColor in styleSheet.IndexedColors)
            {
                toskip++;
                if (toskip <= 8)
                    continue;
                _colors.Add(indexedColor);
            }
        }

        public PaletteRecord()
        {
            
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.Palette;}
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            context.WriteUInt16((ushort) this._colors.Count);
            foreach (var color in _colors)

            {
                context.Write((byte)color.R);
                context.Write((byte)color.G);
                context.Write((byte)color.B);
                context.Write((byte)0);
            }
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            ushort count = context.ReadUInt16();
            for (int i = 0; i < count ;i++)
            {
                var r = context.ReadByte();
                var g = context.ReadByte();
                var b = context.ReadByte();
                context.ReadSByte();
                _colors.Add((Color.FromArgb(255, r, g, b))); 
            }
        }
        public  void Apply(BiffReaderWorkbookContext context)
        {
            context.Workbook.StyleSheet.IndexedColors.Clear();
            List<Color> colors = context.Workbook.StyleSheet.IndexedColors;
            Contract.Assert(colors.Count == 0);
            colors.Add(Color.FromRgb(0x00,0x00,0x00));
            colors.Add(Color.FromRgb(0xff,0xff,0xff));
            colors.Add(Color.FromRgb(0xFF,0x00,0x00));
            colors.Add(Color.FromRgb(0x00,0xFF,0x00));
            colors.Add(Color.FromRgb(0xFF,0xFF,0x00));
            colors.Add(Color.FromRgb(0xFF, 0x00, 0xFF));
            colors.Add(Color.FromRgb(0x00, 0xFF,0xFF));
            colors.Add(Color.FromRgb(0x00,0xFF,0xFF));
            foreach (var color in _colors)
            {
                context.Workbook.StyleSheet.IndexedColors.Add(color);
            }
        }
    }
}